from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic.base import RedirectView
from fruits.models import goods
from django.views.generic import ListView, DetailView
from background.form import FirstForm, ShowFormField, ModelForm1



# Create your views here.
def index(request):
    return HttpResponse('welcome to the management system')


def register(request):
    return render(request, 'register.html')


class R_View(RedirectView):
    pattern_name = 'first:login'
    query_string = True

    def get(self, request, *args, **kwargs):
        print(request.path)
        return super(R_View, self).get(request, *args, **kwargs)


def login(request):
    return render(request, 'login.html')


class ListView1(ListView):
    model = goods
    context_object_name = 'MyGoods'
    template_name = 'listView.html'


class DetailView1(DetailView):
    model = goods
    template_name = 'detailView.html'
    slug_field = 'name'
    slug_url_kwarg = 'name'
    pk_url_kwarg = 'pk'


def CallTemplate(request):
    title = 'hendevy'
    fruits = ['香瓜', '待遇', '黄瓜']
    records = {'鲫鱼':10, '带鱼':20, '鲤鱼':30}
    class Cats(object):
        def __init__(self, name, number, price):
            self.name = name
            self.number = number
            self.price = price
    cats = Cats('hendevy shop', 10, 199)
    #data = goods.objects.all()
    return render(request, 'Template.html', {'title':title, 'dic':records, 'data':cats, 'fruits':fruits})


def HTMLForm(request):
    if request.method == "GET":
        return render(request, 'formtest.html', {'GO': request.path})
    else:
        return HttpResponse('POST is tricked!')


def ShowFirstForm(request):
    if request.method == 'POST':
        form = FirstForm(request.POST)
        if form.is_valid():
            return HttpResponse('response OK!')
    else:
        form = FirstForm()
    return render(request, 'firstForm.html', {'form': form})


def ShowFormField1(request):
    if request.method == 'POST':
        form = ShowFormField(request.POST)
        if form.is_valid():
            return HttpResponse('response OK!')
    else:
        form = ShowFormField()
    #return render(request, 'firstForm.html', {'form': form})
    #return render(request, 'ManualField.html', {'form': form})
    #return render(request, 'traverseField.html', {'form': form})
    return render(request, 'fatherT.html', {'form': form})


def ShowModelForm(request):
    result = goods.objects.all().count()
    obj = goods.objects.filter(id=result).first()
    print(result)
    if request.method == 'GET':
        if obj:
            Mform = ModelForm1(instance=obj)
        else:
            Mform = ModelForm1(instance=None)
        return render(request, 'ModelForm.html', {'Mform':Mform})
    else:
        Mform = ModelForm1(request.POST, instance=obj)
        if Mform.is_valid():
            Mform.save(commit=True)
            return HttpResponse('ModelForm is sent sucessfully!')